<style lang="less" scoped>
@import "../unit-measurement/unitmeasurement.less";
</style>
<template>
  <div>
    <!-- 搜索栏 -->
    <Row style="display:none;">
      <Card>
        <Form ref="search" :model="searchData" :rules="searchReg" :label-width="80">
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="问卷标题" prop="examName">
                <Input
                  v-model="searchData.examName"
                  suffix="ios-search"
                  placeholder="请输入问卷标题"
                  style="width: auto"
                >
                  <Icon type="ios-search" slot="suffix" />
                </Input>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="测评对象">
                <Select
                  clearable
                  placeholder="请选择测评对象"
                  v-model="searchData.listExamers"
                  style="width: 150px"
                >
                  <Option :value="1">县领导</Option>
                  <Option :value="2">党代表</Option>
                  <Option :value="3">人大代表</Option>
                  <Option :value="4">政协委员</Option>
                  <Option :value="5">企业家代表</Option>
                  <Option :value="6">城乡代表</Option>
                  <Option :value="0">无限制</Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="测评单位">
                <Select
                  clearable
                  placeholder="请选择测评单位"
                  v-model="searchData.departCode"
                  style="width:150px"
                >
                  <Option
                    v-for="item in getDepartmentList"
                    :value="item.departcode"
                    :key="item.departcode"
                  >{{ item.department }}</Option>
                </Select>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="开始时间">
                <DatePicker
                  type="date"
                  format="yyyyMMdd"
                  @on-change="searchSelectStart"
                  placeholder="按开始时间搜索"
                  style="width:185px"
                  v-model="searchData.startDate"
                ></DatePicker>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="结束时间">
                <DatePicker
                  type="date"
                  format="yyyyMMdd"
                  @on-change="searchSelectEnd"
                  placeholder="按开始结束时间搜索"
                  style="width:185px"
                  v-model="searchData.endDate"
                ></DatePicker>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="测评对象" prop="testObj" v-show="false || searchData.type === '0'">
                <Select v-model="searchData.testObj" multiple style="width:200px">
                  <Option
                    v-for="item in testObj"
                    :value="item.value.departcode"
                    :key="item.value.departcode"
                  >{{ item.label.department }}</Option>
                </Select>
              </FormItem>
            </i-col>
          </Row>
          <FormItem>
            <Button
              v-if="btnAccess.query"
              type="primary"
              style="marigin:0 20px"
              :loading="searchLoading"
              @click="searchSubmit(10,1)"
            >提交搜索</Button>
            <Button @click="submitReset">重置搜索</Button>
          </FormItem>
        </Form>
      </Card>
    </Row>
    <!-- 表格 -->
    <Row style="margin-top:20px">
      <Card>
        <div class="btn-arrs">
          <Button v-if="btnAccess.add" type="info" @click="insertMeasurement">添加问卷</Button>
        </div>
        <Table
          border
          tooltip
          highlight-row
          :loading="tabelLoading"
          ref="currentRowTable"
          :columns="tabelTitle"
          :data="tabelContent"
          height="500"
        ></Table>
        <div style="margin-top:20px;margin-left:35%">
          <Page
            @on-change="pageNumberChange"
            :page-size="pageSize"
            :total="pageTotal"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-sizer
          />
        </div>
      </Card>
    </Row>
    <!-- 添加/修改测评模态框 -->
    <Modal v-model="isShowModal" :title="modalTitle" @on-cancel="cancelModal" width="700px">
      <Form ref="formsData" :model="formsData" :rules="formReg" :label-width="80">
        <Row>
          <Col span="24">
            <FormItem label="问卷标题" prop="examId">
              <Select v-model="formsData.examId" placeholder="请输入问卷标题" @on-change="titleChange">
                <Option
                  v-for="items in examList"
                  :value="items.id"
                  :key="items.id"
                >{{ items.examName }}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="问卷类别" prop="examType">
              <Select
                v-model="formsData.examType"
                placeholder="请选择类别"
                style="width:190px;"
                disabled
              >
                <Option value="1">类别一</Option>
                <Option value="2">类别二</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="12" v-if="isShowDepart">
            <FormItem label="测评单位">
              <Select
                filterable
                placeholder="请选择测评单位"
                v-model="formsData.departCode"
                style="width:185px;"
              >
                <Option
                  v-for="item in getDepartmentList"
                  :value="item.departcode"
                  :key="item.departcode"
                >{{ item.department }}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="24">
            <FormItem label="测评对象" prop="listExamers">
              <Select v-model="formsData.listExamers" multiple placeholder="请输入测评对象">
                <Option value="1">县领导</Option>
                <Option value="2">党代表</Option>
                <Option value="3">人大代表</Option>
                <Option value="4">政协委员</Option>
                <Option value="5">企业家代表</Option>
                <Option value="6">城乡代表</Option>
                <Option value="0">无限制</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="开始时间" prop="startDate">
              <DatePicker
                type="date"
                format="yyyyMMdd"
                @on-change="modalStartdateFunc"
                :value="formsData.startDate"
                placeholder="请选择开始时间"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="结束时间" prop="endDate">
              <DatePicker
                type="date"
                format="yyyyMMdd"
                @on-change="modalEnddateFunc"
                :value="formsData.endDate"
                placeholder="请选择开始时间"
              ></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button
          v-if="btnAccess.upd"
          type="primary"
          size="large"
          :loading="modalLoading"
          @click="submitModal"
        >提交</Button>
        <Button size="large" @click="cancelModal">取消</Button>
      </div>
    </Modal>
    <!-- 查看统结果侧边栏 -->
    <Drawer
      @on-close="closeDrawer"
      :title="deawerTitle"
      v-model="isShowDrawer"
      :msk-closable="false"
      width="100%"
      :styles="styles"
    >
      <Row>
        <Card>
          <Tabs value="name1">
            <!-- 表格视图 -->
            <TabPane label="表格视图" name="name1">
              <Table
                sum-text="合计"
                show-summary
                border
                stripe
                :columns="resultHead"
                :data="resultDatas"
                height="500"
              ></Table>
            </TabPane>
            <!-- 问卷视图 -->
            <TabPane label="问卷视图" name="name2">
              <div style="height:500px;overflow-y:scroll;">
                <div class="containers">
                  <div class="titles" v-for="(item,index) in result" :key="index">
                    <h3>{{item.stem}}</h3>
                    <RadioGroup class="radio-container" vertical>
                      <Radio
                        v-for="(items , indexs) in item.selectList"
                        :key="indexs"
                        :label="items.selectId"
                        :disabled="true"
                      >
                        {{items.selectItem}}：
                        <span class="grenFont">{{items.count}}</span> 个
                      </Radio>
                    </RadioGroup>
                  </div>
                </div>
              </div>
            </TabPane>
          </Tabs>
        </Card>
      </Row>
    </Drawer>
  </div>
</template>
<script>
import { questionMangeAjax } from "@/api/measurement";
// 查询
const QUERY_URL = "/examManage/query";
// 添加URL
const INSERT_URL = "/examManage/insert";
// 修改URL
const UPDATE_URL = "/examManage/update";
// 删除
const DELETE_URL = "/examManage/delete";
// 查询问卷作答的结果
const QUERYRESULT_UTL = "/examManage/singleExamResult";
const INSERT_TITLE = "添加问卷";
const UPDATE_TITLE = "编辑问卷";
export default {
  data() {
    return {
      // 增删改查权限按钮
      btnAccess: {
        add: true,
        add2: "inline-block",
        del: "inline-block",
        upd: true,
        query: true
      },
      isShowDepart: false, // 是否显示单位
      tabelLoading: false,
      searchLoading: false,
      searchData: {
        testObj: [],
        departCode: "",
        examName: "", // 问卷标题
        examType: "", // 问卷类别
        listExamers: [], // 测评对象
        startDate: "",
        endDate: ""
      },
      tabelTitle: [
        {
          title: "问卷标题",
          key: "examName"
        },
        {
          title: "测评对象",
          key: "examer"
        },
        {
          title: "测评单位",
          key: "department"
        },
        {
          title: "开始时间",
          key: "startDate"
        },
        {
          title: "结束时间",
          key: "endDate"
        },
        {
          title: "操作",
          key: "action",
          width: 270,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.formsData = Object.assign({}, params.row);
                      // 获取问卷类型
                      let title = params.row.examId; // 问卷id
                      this.examList.forEach(item => {
                        if (item.id === title) {
                          this.formsData.examType = item.examType;
                          // 一类不需要显示单位
                          if (item.examType === "1") {
                            this.isShowDepart = false;
                          } else {
                            this.isShowDepart = true;
                          }
                        }
                      });
                      this.modalTitle = UPDATE_TITLE;
                      this.isShowModal = true;
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "success",
                    size: "small"
                  },
                  style: {
                    margin: "0 10px"
                  },
                  on: {
                    click: () => {
                      let item = params.row;
                      this.formsData = Object.assign({}, item);
                      this.deawerTitle = item.examName + " -------- 统计结果";
                      this.isShowDrawer = true;
                      // 查询问卷结果
                      this._queryResultAjax(item, QUERYRESULT_UTL);
                    }
                  }
                },
                "查看测评结果"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  style: {
                    display: this.btnAccess.del
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: "删除测评",
                        content: "<p>删除后将无法恢复！</p>",
                        loading: true,
                        onOk: () => {
                          var formData = Object.assign(
                            {},
                            {
                              id: params.row.id
                            }
                          );
                          var url = DELETE_URL;
                          var keyOne = "entity";
                          questionMangeAjax({ formData, url, keyOne })
                            .then(result => {
                              this.$Modal.remove();
                              if (
                                result.data.code === "200" &&
                                result.data !== undefined
                              ) {
                                this.$Message.success("删除成功");
                                this._getQuestionMangeData(
                                  this.searchData,
                                  this.pageSize,
                                  this.pageNumber
                                );
                              } else {
                                this.$Message.error(result.data.message);
                              }
                            })
                            .catch(err => {
                              console.log(err);
                            });
                        }
                      });
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      tabelContent: [],
      examList: [], // 标题下拉框
      searchReg: {},
      pageTotal: 10,
      pageNumber: 1,
      pageSize: 10,
      testObj: [],
      // 弹窗form 表单
      formsData: {
        examName: "", // 问卷标题
        listExamers: [], // 测评对象
        examId: 0,
        examType: "", // 问卷类别
        departCode: "",
        startDate: "",
        endDate: "",
        datetime: ""
      },
      modalTitle: "添加",
      isShowModal: false,
      modalLoading: false,
      // 模态框form 表单
      formReg: {
        examId: [
          {
            required: true,
            type: "number",
            message: "请选择问卷标题",
            trigger: "change"
          }
        ],
        listExamers: [
          {
            required: true,
            type: "array",
            message: "请选择测评对象",
            trigger: "change"
          }
        ],
        startDate: [
          {
            required: true,
            type: "string",
            message: "请选择年份",
            trigger: "change"
          }
        ],
        endDate: [
          {
            required: true,
            type: "string",
            message: "请选择年份",
            trigger: "change"
          }
        ]
      },
      // 查看统计结构侧边栏
      isShowDrawer: false,
      deawerTitle: "",
      styles: {
        height: "calc(100% - 55px)",
        overflow: "auto",
        paddingBottom: "53px",
        position: "static"
      },
      result: [], // 作答结果
      // 测评结果
      resultHead: [
        {
          title: "题干",
          key: "stem"
        },
        {
          title: "A",
          key: "A",
          sortable: true
        },
        {
          title: "B",
          key: "B",
          sortable: true
        },
        {
          title: "C",
          key: "C",
          sortable: true
        },
        {
          title: "D",
          key: "D",
          sortable: true
        },
        {
          title: "E",
          key: "E",
          sortable: true
        },
        {
          title: "F",
          key: "F",
          sortable: true
        }
      ],
      resultDatas: []
    };
  },
  methods: {
    // 添加测评
    insertMeasurement() {
      this.modalTitle = INSERT_TITLE;
      this.isShowModal = true;
      this.$refs["formsData"].resetFields();
      this.formsData.id = ""; // 清除id
    },
    // 开始日期
    searchSelectStart(date) {
      this.searchData.startDate = date;
    },
    // 截止日期
    searchSelectEnd(date) {
      this.searchData.endDate = date;
    },
    // 页码
    pageNumberChange(pageNumber) {
      this.pageNumber = pageNumber;
      this._getQuestionMangeData(
        this.searchData,
        this.pageSize,
        this.pageNumber
      );
    },
    // 页数
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this._getQuestionMangeData(
        this.searchData,
        this.pageSize,
        this.pageNumber
      );
    },
    submitReset() {
      this.searchData = {
        testObj: [],
        name: "",
        type: "",
        startDate: "",
        endDate: ""
      };
      this.searchLoading = false;
    },
    // 搜索提交
    searchSubmit(pageSize, pageNumber) {
      this.pageSize = pageSize;
      this.pageNumber = pageNumber;
      this.searchLoading = true;
      this._getQuestionMangeData(
        this.searchData,
        this.pageSize,
        this.pageNumber
      );
    },
    // 查询
    _getQuestionMangeData(searchData, pageSize, pageNumber) {
      this.tabelLoading = true;
      var url = QUERY_URL;
      var keyOne = "filter";
      var formData = Object.assign(searchData, {
        pageSize: pageSize,
        pageNumber: pageNumber
      });
      questionMangeAjax({ formData, url, keyOne })
        .then(result => {
          this.tabelLoading = false;
          this.searchLoading = false;
          if (result.data.code === "200" && result.data !== undefined) {
            this.tabelContent = result.data.results.list;
            this.examList = result.data.results.examList;
            this.pageTotal = parseInt(result.data.results.pageTotal);
          } else {
            this.$Message.error(result.data.message);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 模态框事件
    cancelModal() {
      this.isShowModal = false;
      this.modalLoading = false;
    },
    modalDatetimeFunc(date) {
      this.formsData.datetime = date;
    },
    modalStartdateFunc(date) {
      this.formsData.startDate = date;
    },
    modalEnddateFunc(date) {
      this.formsData.endDate = date;
    }, // 添加/修改
    _addOrUpdDataAjax(formData, url) {
      const keyOne = "entity";
      return new Promise((resolve, reject) => {
        questionMangeAjax({ formData, url, keyOne })
          .then(result => {
            if (result.data !== undefined) {
              resolve(result.data);
            } else {
              reject(err);
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 提交模态框
    submitModal() {
      this.$refs["formsData"].validate(valid => {
        if (valid) {
          // 结束时间不能早于开始时间
          if (
            parseInt(this.formsData.startDate) >
            parseInt(this.formsData.endDate)
          ) {
            this.$Notice.error({
              title: "结束时间不能早于开始时间",
              duration: 5
            });
            return;
          }
          this.modalLoading = true;
          if (this.modalTitle === INSERT_TITLE) {
            this._addOrUpdDataAjax(this.formsData, INSERT_URL).then(result => {
              this.isShowModal = false;
              this.modalLoading = false;
              if (result.code === "200") {
                this.$Message.success("添加成功！");
                this._getQuestionMangeData(
                  this.searchData,
                  this.pageSize,
                  this.pageNumber
                );
              } else {
                this.$Message.error(result.message);
              }
            });
          } else if (this.modalTitle === UPDATE_TITLE) {
            this._addOrUpdDataAjax(this.formsData, UPDATE_URL).then(result => {
              this.isShowModal = false;
              this.modalLoading = false;
              if (result.code === "200") {
                this.$Message.success("修改成功！");
                this._getQuestionMangeData(
                  this.searchData,
                  this.pageSize,
                  this.pageNumber
                );
              } else {
                this.$Message.error("修改失败！");
              }
            });
          }
        } else {
          this.$Message.error("请填写完整！");
        }
      });
    },
    /**
     *  // 问卷标题联动问卷类别
     * @param value  改变的返回值
     */
    titleChange(value) {
      this.examList.forEach(item => {
        if (item.id === value) {
          this.formsData.examType = item.examType;
          // 一类不需要显示单位
          if (item.examType === "1") {
            this.isShowDepart = false;
          } else {
            this.isShowDepart = true;
          }
        }
      });
    },
    // 关闭侧边栏
    closeDrawer() {
      this.isShowDrawer = false;
    },
    // 查询作答结果
    _queryResultAjax(formData, url) {
      const keyOne = "filter";
      questionMangeAjax({ formData, url, keyOne })
        .then(result => {
          if (result.data.code === "200") {
            this.result = result.data.results.list;
            this.resultDatas = result.data.results.tableList;
            this.$Message.success(result.data.message);
          } else {
            this.$Message.error(result.data.message);
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  created() {
    this._getQuestionMangeData(this.searchData, this.pageSize, this.pageNumber);
    // 获取按钮权限
    let btnAccess = sessionStorage.getItem("btnaccess");
    this.globalFunction(btnAccess);
  },
  computed: {
    getDepartmentList() {
      return this.$store.state.user.departmentList;
    }
  }
};
</script>
<style>
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
.grenFont {
  color: green;
  font-size: 15px;
}
</style>
